jQuery(document).ready(function(){
	
	// append float box into end of document
	jQuery("body").append(jQuery("#floatbox_wrapper").html());
	jQuery("#floatbox_wrapper").html("");
	
	// auto center the loading
	jQuery.fn.centerScreen = function(loaded) { 
		var obj = this; 
		if(!loaded) { 
			obj.css('top', $(window).height()/2- this.height()/2); 
			obj.css('left', $(window).width()/2- this.width()/2); 
			$(window).resize(function() 
			{ obj.centerScreen(!loaded); }); 
		} else { 
			obj.stop(); 
			obj.animate({ top: $(window).height()/2 - this.height()/2, left: $(window).width()/2-this.width()/2}, 200, 'linear'); 
		} 
	};

	// center the loading         
	//_abpv_centerLoading();
	jQuery("#abpv_loadingDiv").centerScreen(true);
	$(window).bind('resize', function() {
		jQuery("#abpv_loadingDiv").centerScreen(false);
	});
	$(window).bind('scroll', function() {
		jQuery("#abpv_loadingDiv").centerScreen(false);
	});

	// for button hover
	jQuery(".goog-imageless-button").hover(function(){
		jQuery(this).addClass("goog-imageless-button-hover");
	}, function(){
		jQuery(this).removeClass("goog-imageless-button-hover");
	})

	// navBack, navForward
	jQuery("#navBack").click(function(){
		wfirst_day-=24*3600*7; // back one week
		wlast_day-=24*3600*7;
		ReloadCalendar();
	});
	jQuery("#navForward").click(function(){
		wfirst_day+=24*3600*7; // back one week
		wlast_day+=24*3600*7;
		ReloadCalendar();
	})

	jQuery(".bubbleclose").click(function(){
		jQuery("#ab_calendar_dialog").fadeOut();
	});
	
	// first, check if there is a hash inputed
	var date_hash=window.location.hash;
	if (date_hash.length > 0)
	{
		date_hash=date_hash.substr(1);
		var parsetemp=date_hash.match(/(\d+)/g);
		if (parsetemp.length==6){
			var date_hash=new Date(parseInt(parsetemp[0]),parseInt(parsetemp[1])-1,parseInt(parsetemp[2]),0,0,0);
			wfirst_day=date_hash.getTime()/1000;
			bkwfirst_day=wfirst_day;
			
			var date_hash=new Date(parseInt(parsetemp[3]),parseInt(parsetemp[4])-1,parseInt(parsetemp[5]),23,59,59);
			wlast_day=date_hash.getTime()/1000;
			bkwlast_day=wfirst_day;
		}
	}
	// call js to load date in calendar
	ReloadCalendar();

	// for delete, edit of float box
	jQuery(".eb-actions-left a").click(function(){ // for delete button
		var id=jQuery(this).attr("rel");
		if (id > 0)
			window.location="/index.php?module=calendarmodule&action=delete&id="+id+"&src="+__location_src;
	});

	jQuery(".eb-actions-right a").click(function(){ // for edit button
		var id=jQuery(this).attr("rel");
		if (id > 0)
			window.location="/index.php?module=calendarmodule&action=edit&id="+id+"&src="+__location_src;
	});
	
	jQuery("#mg-refresh").click(function(){
		ReloadCalendar();
	})
	
	jQuery("#todayButton").click(function(){
	   wfirst_day = bkwfirst_day;
	   wlast_day = bkwlast_day;
	   ReloadCalendar();
	});
});


var __location_src='';
function __abpv_SetDefaultSource(location_src){
	__location_src=location_src;
}

function _abpv_showLoading(){
	jQuery('#abpv_loadingDiv').fadeIn();
}

function _abpv_hideLoading(){
	jQuery('#abpv_loadingDiv').fadeOut();
}

/**
* This function will clear all current data in table
*/
function AB_Calendar_clear(){
	
	// clear today selector
	jQuery("#ab_calendar_dialog").fadeOut();
	jQuery(".tg-today").remove();
	jQuery(".wk-today").removeClass("wk-today");
	jQuery(".tg-col-today").removeClass("tg-col-today").addClass("tg-col");
	jQuery("#tgnowmarker").remove();
	jQuery(".chip").fadeOut("fast", function(){
		jQuery(this).remove();
	});
	// force clear
	for (var i=0;i<7;i++)
	  jQuery("#tgCol"+i+" .tg-gutter").html("");
}

/**
* Convert form unix timestamp to js datetime
* @author trungdt
* @since Nov 4, 2011
*/
function AB_DateConvert(value){
	var newDate=new Date();
	newDate.setTime(value*1000);
	return newDate;
}

/**
* This function add a day into current date
* @author trungdt
* @since Nov 4, 2011
*/
function AB_DateAddDay(value){
	var newDate=new Date(value.getTime()+86400000);
	return newDate;
}

/**
* Reload calendar by inputed params: today, begin of today, wfirst day, wlast day
*/
function ReloadCalendar(){
	_abpv_showLoading();
	jQuery.get(link_url, {
		from_date: wfirst_day,
		to_date: wlast_day,
		ajax_action: 1,
		t: Math.random()
	}, function (data){
		_abpv_hideLoading();	
		var dfirst_day=AB_DateConvert(wfirst_day);
		var dlast_day=AB_DateConvert(wlast_day);
		
		// update url
		var url_href=dfirst_day.getFullYear()+"-"+(parseInt(dfirst_day.getMonth())+1)+"-"+dfirst_day.getDate()+"::"+dlast_day.getFullYear()+"-"+(parseInt(dlast_day.getMonth())+1)+"-"+dlast_day.getDate();
		window.location.hash="#"+url_href;

		// clear data
		AB_Calendar_clear();
		
		// show day length, in top-left
		if (dfirst_day.getFullYear() == dlast_day.getFullYear() && dfirst_day.getMonth() == dlast_day.getMonth())
			{
			jQuery("#currentDate").html(dfirst_day.getDate()+" - "+dlast_day.getDate()+" "+lang_month+" "+(dlast_day.getMonth()+1)+","+dfirst_day.getFullYear());
		}
		else if (dfirst_day.getFullYear() == dlast_day.getFullYear())
			{
			jQuery("#currentDate").html(dfirst_day.getDate()+" "+lang_month+" "+(dfirst_day.getMonth()+1)+" - "+dlast_day.getDate()+" "+lang_month+" "+(dlast_day.getMonth()+1)+ ","+dfirst_day.getFullYear());
		}
		else
			{
			jQuery("#currentDate").html(dfirst_day.getDate()+" "+lang_month+" "+(dfirst_day.getMonth()+1)+","+dfirst_day.getFullYear() + " - "+dlast_day.getDate()+" "+lang_month+" "+(dlast_day.getMonth()+1)+ ","+dlast_day.getFullYear());
		}

		// select today
		// today col select
		if ((today >=wfirst_day) && (today <= wlast_day))
			{ // only show today column if today is in between of first day and last day
			var currentDate = new Date()
			var current_day=currentDate.getDay();
			jQuery("#ab_calendar_cols td:eq("+current_day+")").removeClass("tg-col").addClass("tg-col-today");
			jQuery("#ab_calendar_cols td:eq("+current_day+")").html(jQuery("#ab_calendar_cols td:eq("+current_day+")").html()+'<div class="tg-today" style="height:1008px;margin-bottom:-1008px;">&nbsp;</div>');
			jQuery(".tg-label td:eq("+current_day+")").addClass("wk-today");
			var current_time=currentDate.getHours()-7;
			var current_min=currentDate.getMinutes();
			if (current_time < (23-7)) // dont show after 23:00
				jQuery("#tgOver"+(current_day-1)).html('<div class="tg-hourmarker tg-nowmarker" id="tgnowmarker" style="top: '+(42*current_time+current_min*42/60)+'px;"> </div>');
		}

		// set date of each day of week
		dfirst_day=AB_DateConvert(wfirst_day);
		for (var i=0; i<7;i++)
		{
			if (i>0)
				dfirst_day=AB_DateAddDay(dfirst_day);
			jQuery("#tgTable .tg-label td.tg-col:eq("+i+") > span").html(dfirst_day.getDate()+"/"+(dfirst_day.getMonth()+1));
		}


		// load data into grid
		var obj = eval('(' + data + ')');
		AddEvent_toGrid(obj.rows);
		/*for (var i=0;i<obj.rows.length;i++)
		{
			cur_obj=obj.rows[i];
			AddEvent_toGrid(cur_obj);
		}*/
		jQuery(".tg-col-today .chip").each(function(){
			jQuery(this).css("top", (parseInt(jQuery(this).css("top"))+3)+"px");
		});
		jQuery(".chip").fadeIn();

		// event handler when click on event
		jQuery(".chip").click(function(){
			var title=jQuery(this).attr("title");
			var id=jQuery(this).attr("rel_id");
			var body=jQuery("#event_body_"+id).html();
			var full_date=jQuery(this).attr("rel_fulldate");
			var cat_name=jQuery(this).attr("rel_catname");
			var relative=parseInt(jQuery(this).attr("rel_relative"));
			var relative_index=parseInt(jQuery(this).attr("rel_relative_index"));
			if (cat_name.length > 0)
				full_date+="<br>"+cat_name;
			var day_of_week=parseInt(jQuery(this).attr("rel_day_of_week"))-1.5;
			var cur_top=parseInt(jQuery(this).attr("rel_top"));

			// set data
			jQuery("#mtb .ui-sch-schmedit").html(title);
			jQuery("#ab_dialog_date").html(full_date);
			jQuery("#ab_dialog_content").html(body);

			// permission
			if (parseInt(jQuery(this).attr("pe")) == 1)
				jQuery(".eb-actions-right a").attr("rel",id).show();
			else
				jQuery(".eb-actions-right a").attr("rel",-1).hide();

			if (parseInt(jQuery(this).attr("pd")) == 1)
				jQuery(".eb-actions-left a").attr("rel",id).show();
			else
				jQuery(".eb-actions-left a").attr("rel",-1).hide();

			// set position
			//var pos=jQuery(this).position();
			var pos=jQuery(this).offset();
			//pos.left+=jQuery(this).width()*day_of_week+jQuery(window).pageXOffset;
			//pos.top=cur_top-25+jQuery(window).pageXOffset;
			//pos.left+=parseInt(jQuery(window)[0].scrollX);
			//pos.top+=parseInt(jQuery(window)[0].scrollY);
			
			pos.left-=jQuery("#ab_calendar_dialog").width()/2+parseFloat(jQuery(this).css("left"))-((94/(relative+1))*(relative_index+1));
			if (relative_index > 1)
				pos.left+=jQuery(this).width()/2;
			else if (relative_index > 0)
				pos.left+=jQuery(this).width()/3;
			pos.top-=jQuery("#ab_calendar_dialog").height()+15;
			
			jQuery("#ab_calendar_dialog").css(pos);

			jQuery("#ab_calendar_dialog").fadeIn();
		});
	});
}

// New version: Nov 10, 2011
function AddEvent_toGrid(obj_rows){
	
	for (var i=0;i<obj_rows.length;i++){
		var cur_obj=obj_rows[i];
		
		var cur_day=AB_DateConvert(cur_obj.eventstart);
		var cur_day2=new Date();
		
		// for color
		var cur_top, cur_height, cur_left, cur_width;
		if (cur_obj.approve == 0)
			cur_obj.cat_color=color_waiting;
		if (cur_obj.approve == 1)
			cur_obj.cat_color=color_not_approve;
			
		// calculate top  and height
		cur_top=42*(parseInt(cur_obj.fhour)-7)+parseInt(cur_obj.fmin)*41/60;
		cur_height = 42*(parseInt(cur_obj.thour)-parseInt(cur_obj.fhour)-1)+((60-parseInt(cur_obj.fmin))+parseInt(cur_obj.tmin))*41/60;
		
		//calculate width and left
		cur_left=0; cur_width=0;
		var cur_index_appear=0;
		var cur_appear=false;
		for (var k=0;k<obj_rows.length;k++)
		{
			if (cur_obj.id == obj_rows[k].id)
				cur_appear=true;
			if (
			((cur_obj.eventstart>=obj_rows[k].eventstart) && (cur_obj.eventstart<=obj_rows[k].eventend))
			||
			((cur_obj.eventend>=obj_rows[k].eventstart) && (cur_obj.eventend<=obj_rows[k].eventend)) ||
			((obj_rows[k].eventstart>=cur_obj.eventstart) && (obj_rows[k].eventstart<=cur_obj.eventend))
			||
			((obj_rows[k].eventend>=cur_obj.eventstart) && (obj_rows[k].eventstart<=cur_obj.eventend))
			)
			{
				cur_left++;
				if (!cur_appear)
					cur_index_appear++;
			}
		}
		var count_relative=cur_left;
		//alert(cur_left);			
		cur_width=94/parseFloat(cur_left);
		cur_left=cur_width*(cur_index_appear);
		
		var html='<div id="event_'+cur_obj.id+'" rel_relative_index="'+cur_index_appear+'" rel_relative="'+count_relative+'" rel_top="'+cur_top+'" rel_day_of_week="'+(cur_obj.day_of_week)+'" pe="'+cur_obj.permission_edit+'" pd="'+cur_obj.permission_delete+'" rel_id="'+cur_obj.real_id+'" rel_fulldate="'+cur_obj.full_date+'" title="'+cur_obj.title+'" rel_catname="'+cur_obj.category+'" class="chip" style="top: '+cur_top+'px;left: '+cur_left+'px;width:'+cur_width+'px; display: none;"><dl class="cbrd" style="height:'+cur_height+'px;border-color:#9FC6E7;background-color:'+cur_obj.cat_color+';color:#777777;"><dt style="background-color: none;">'+cur_obj.fhour+':'+cur_obj.fmin+'-'+cur_obj.thour+':'+cur_obj.tmin+' </dt><dd><span>'+cur_obj.title+'</span></dd></dl><span id="event_body_'+cur_obj.id+'" style="display: none;">'+cur_obj.body+'</span></div>';

		jQuery("#tgCol"+(cur_obj.day_of_week)+" div.tg-gutter").append(html);
	}	
}

/*function AddEvent_toGrid(cur_obj){
	var cur_day=AB_DateConvert(cur_obj.eventstart);
	var cur_day2=new Date();
	
	// for color
	var cur_obj, cur_top, cur_height;
	if (cur_obj.approve == 0)
		cur_obj.cat_color=color_waiting;
	if (cur_obj.approve == 1)
		cur_obj.cat_color=color_not_approve;

	// calculate top  and height
	cur_top=42*(parseInt(cur_obj.fhour)-7)+parseInt(cur_obj.fmin)*41/60;
	cur_height = 42*(parseInt(cur_obj.thour)-parseInt(cur_obj.fhour)-1)+((60-parseInt(cur_obj.fmin))+parseInt(cur_obj.tmin))*41/60;
	
	var fake_index, i;
	var first_day=AB_DateConvert(wfirst_day);
	var last_day=AB_DateConvert(wlast_day);
	
	var cur_end=AB_DateConvert(cur_obj.eventend);
	if (cur_obj.repeat_type == 0)
	{
		if ((wfirst_day <= cur_obj.eventstart) && (wlast_day >=cur_obj.eventstart))
			i=cur_day.getDay();
		else
			i=0;
		if ((wfirst_day <= cur_obj.eventend) && (wlast_day >=cur_obj.eventend))
			fake_index=cur_end.getDay();
		else
			fake_index=7;
	}
	else 
	{
		fake_index=parseInt(cur_obj.day_of_week)+1;
		i=parseInt(cur_obj.day_of_week);
	}
	
	for (i=i;i<fake_index;i++){
		
		// build object
		var html='<div id="event_'+cur_obj.id+'_'+i+'" rel_top="'+cur_top+'" rel_day_of_week="'+(i+1)+'" pe="'+cur_obj.permission_edit+'" pa="'+cur_obj.permission_approve+'" pd="'+cur_obj.permission_delete+'" rel_id="'+cur_obj.id+'" rel_fulldate="'+cur_obj.full_date+'" title="'+cur_obj.title+'"  class="chip" style="top: '+cur_top+'px;left:-1px;width:100%; display: none;"><dl class="cbrd" style="height:'+cur_height+'px;border-color:#9FC6E7;background-color:'+cur_obj.cat_color+';color:#777777;"><dt style="background-color: none;">'+cur_obj.fhour+':'+cur_obj.fmin+'-'+cur_obj.thour+':'+cur_obj.tmin+' </dt><dd><span>'+cur_obj.title+'</span></dd></dl><span id="event_body_'+cur_obj.id+'" style="display: none;">'+cur_obj.body+'</span></div>';

		jQuery("#tgCol"+i+" div.tg-gutter").append(html);
	}
}*/

// parse a date in yyyy-mm-dd format
// @author: trungdt 
// @since Nov 6, 2011
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}